"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 硬件故障类--network
Case Name   : gs_basebackup备份时主节点网卡down
Create At   : 2021/09/17
@zou_jialiang0505328126
Description :
    1. 主节点执行备份指令
    2.备份的同时注入网卡down故障
    3. 使用备份文件恢复系统
    4.对备库进行build
    5.查询数据是否与备份时一致
Expect      :
    1.可能因为网络中断失败
    2.成功
    3.成功
    4.成功
    5.数据一致，且主备一致
History     :
"""

import unittest
import os
import time
from yat.test import Node, macro
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread


class CPUOverloadAndRunTPCC(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(
            '---------Opengauss_Reliability_Hardware_Case121:开始执行---------')
        self.primary_root_node = Node(node='PrimaryRoot')
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.sta1_dbuser = Node(node='Standby1DbUser')
        self.sta2_dbuser = Node(node='Standby2DbUser')
        self.com = Common()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.sta_1_sh = CommonSH('Standby1DbUser')
        self.sta_2_sh = CommonSH('Standby2DbUser')
        self.constant = Constant()
        self.parent_path = os.path.dirname(macro.DB_INSTANCE_PATH)
        self.backup_path = os.path.join(self.parent_path, 'base_backup')
        self.flg = True

        result = self.primary_sh.executDbSql(
            'show wal_sender_timeout;')
        self.log.info(f"wal_sender_timeout is {result}")
        self.wal_sender_timeout = result.strip().splitlines()[-2]

        self.log.info("-------------获取网卡名---------------")
        network_card_cmd = 'ifconfig'
        self.log.info(network_card_cmd)
        network_card_result = self.primary_root_node.sh(
            network_card_cmd).result()
        network_card_list = network_card_result.split('\n\n')
        self.log.info(network_card_list)
        self.networkcard = ''
        for network_card_item in network_card_list:
            if self.primary_user_node.db_host in network_card_item:
                self.networkcard = network_card_item.split(':')[0].strip()
                self.log.info(self.networkcard)

    def test_main(self):
        backup_text = '----step1: 主节点执行备份指令 expect:可能因为网络中断失败----'
        self.log.info(backup_text)
        shell_cmd = f'rm -rf {self.backup_path}; mkdir {self.backup_path}'
        self.log.info(shell_cmd)
        result = self.primary_user_node.sh(shell_cmd).result()
        self.log.info(result)
        backup_thread = ComThread(self.primary_sh.execu_gs_basebackup, args=(
            self.backup_path, self.primary_user_node.db_host,
            self.primary_user_node.db_port))
        backup_thread.setDaemon(True)
        backup_thread.start()

        text = '----step2: 备份的同时注入网卡down故障 expect:成功----'
        self.log.info(text)
        inject_command = f"rNet_down (dev, time)" \
            f"values({self.networkcard}, 15)"
        cfe_thread = ComThread(
            self.com.cfe_inject, args=(self.primary_root_node,
                                       inject_command,))
        cfe_thread.setDaemon(True)
        cfe_thread.start()
        cfe_thread.join(20)
        result = cfe_thread.get_result()
        self.log.info(result)
        self.assertIn(self.constant.cfe_inject_netdown_success_msg, result,
                      '执行失败' + text)

        self.log.info("------------获取备份结果-----------------")
        backup_thread.join(1800)
        result = backup_thread.get_result()
        self.log.info(result)
        if self.constant.BASEBACKUP_SUCCESS_MSG not in result:
            time.sleep(15)
            shell_cmd = f'rm -rf {self.backup_path}; mkdir {self.backup_path}'
            self.log.info(shell_cmd)
            result = self.primary_user_node.sh(shell_cmd).result()
            self.log.info(result)
            result = self.primary_sh.execu_gs_basebackup(
                self.backup_path, self.primary_user_node.db_host,
                self.primary_user_node.db_port)
            self.log.info(result)
            self.assertIn(self.constant.BASEBACKUP_SUCCESS_MSG, result,
                          '执行失败:恢复故障后备份依旧失败')

        text = '----step3: 使用备份文件恢复数据库 expect:成功----'
        self.log.info(text)
        result = self.primary_sh.stopDbCluster()
        self.assertTrue(result, '执行失败:' + text)
        shell_cmd = f'rm -rf  {macro.DB_INSTANCE_PATH}/* ;' \
            f'cp -R {self.backup_path}/* {macro.DB_INSTANCE_PATH}'
        self.log.info(shell_cmd)
        result = self.primary_user_node.sh(shell_cmd).result()
        self.log.info(result)
        time.sleep(2)
        result = self.primary_sh.startDbCluster('get_detail')
        self.log.info(result)
        result = ('Degraded' in result) or \
                 (self.constant.START_SUCCESS_MSG in result)
        self.assertTrue(result, '执行失败:' + text)
        time.sleep(2)
        text = '----step4: 对备库进行build expect:成功----'
        self.log.info(text)
        result = self.primary_sh.check_whether_need_build()
        success_msg = self.constant.BUILD_SUCCESS_MSG
        if result:
            result = self.sta_1_sh.executeGsctl('build',
                                                success_msg,
                                                '-b full')
            self.assertTrue(result, '执行失败:' + text)
            result = self.sta_2_sh.executeGsctl('build',
                                                success_msg,
                                                '-b full')
            self.assertTrue(result, '执行失败:' + text)
        self.flg = False

        text = '----step5: 查询数据是否与备份时一致 expect:数据一致，且主备一致----'
        self.log.info(text)
        result = self.sta_1_sh.check_data_consistency()
        self.assertTrue(result, '执行失败:' + text)
        result = self.sta_2_sh.check_data_consistency()
        self.assertTrue(result, '执行失败:' + text)
        nodes_tuple = (self.primary_user_node,
                       self.sta1_dbuser, self.sta2_dbuser)
        flag = self.com.check_data_sample_by_all(r'\d', *nodes_tuple)
        self.assertTrue(flag, '执行失败:' + text)

        table_dict = self.com.format_sql_result(
            self.primary_sh.executDbSql(r'\d'))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = self.com.check_data_sample_by_all(select_sql,
                                                        *nodes_tuple)
            self.assertTrue(flag, '执行失败:' + text)

    def tearDown(self):
        if self.flg:
            self.log.info("等待故障结束")
            time.sleep(15)
        self.log.info('----删除备份文件----')
        shell_cmd = f'rm -rf {self.backup_path}'
        self.log.info(shell_cmd)
        result = self.primary_root_node.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info('----检查备机是否需要重建----')
        result = self.primary_sh.check_whether_need_build()
        if result:
            self.sta_1_sh.executeGsctl('build',
                                       self.constant.BUILD_SUCCESS_MSG,
                                       '-b full')
            self.sta_2_sh.executeGsctl('build',
                                       self.constant.BUILD_SUCCESS_MSG,
                                       '-b full')

        self.log.info('-----------还原wal_sender_timeout------------------')
        result = self.primary_sh.executeGsguc('reload',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          f'wal_sender_timeout='
                                          f'{self.wal_sender_timeout}')
        self.log.info(result)
        self.log.info(
            '--------Opengauss_Reliability_Hardware_Case121:执行完成--------')
